package com.snow.fkisoftstone;

import android.accessibilityservice.AccessibilityService;
import android.os.Environment;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.snow.fkisoftstone.bean.WorkTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Predicate;

public class TimerService extends AccessibilityService {
    private static final String TAG = "TimerService";


    public static final String PATH_LOG = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Timer/timer.log";
    public static final String PATH_DATE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Timer/timer_%s.dat";

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // 获取包名
        String pkgName = event.getPackageName().toString();
        int eventType = event.getEventType();
//        com.isoftstone.client.ipsa:id/tv_today  日期
//        com.isoftstone.client.ipsa:id/week    星期
//        com.isoftstone.client.ipsa:id/moring_time_tv 上班打卡时间
//        上班打卡成功
//        下班打卡成功
//            TYPE_WINDOW_STATE_CHANGED
//            TYPE_WINDOW_CONTENT_CHANGED
        try {
            AccessibilityNodeInfo nodeInfo = event.getSource();
            if (nodeInfo == null) {
                return;
            }
            Log.d(TAG, eventType + "___" + nodeInfo.toString());


            if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                //点击时触发
                AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
                List<AccessibilityNodeInfo> startTimeLists = accessibilityNodeInfo.
                        findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/moring_time_tv");
                List<AccessibilityNodeInfo> todayLists = accessibilityNodeInfo.
                        findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/tv_today");
                List<AccessibilityNodeInfo> weekLists = accessibilityNodeInfo.
                        findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/week");
                String startTime = getValue(startTimeLists);
                String today = getValue(todayLists);
                String week = getValue(weekLists);

//                Date d = new Date();
//                SimpleDateFormat sbf = new SimpleDateFormat("HH:mm");
//                String endTime = sbf.format(d);

                //2022-03-28 星期一 null 08:36
                //2022-03-28 星期一 08:36 20:15
                //null null null 20:15
                inserData(today, week, startTime, null, eventType);


            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
                List<AccessibilityNodeInfo> endLists = accessibilityNodeInfo.findAccessibilityNodeInfosByText("下班打卡成功");
                if (endLists != null && endLists.size() > 0) {
                    //下班打卡成功时
                    List<AccessibilityNodeInfo> startTimeLists = accessibilityNodeInfo.
                            findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/moring_time_tv");
                    List<AccessibilityNodeInfo> todayLists = accessibilityNodeInfo.
                            findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/tv_today");
                    List<AccessibilityNodeInfo> weekLists = accessibilityNodeInfo.
                            findAccessibilityNodeInfosByViewId("com.isoftstone.client.ipsa:id/week");

                    //下班打卡时触发
                    String startTime = getValue(startTimeLists);
                    String today = getValue(todayLists);
                    String week = getValue(weekLists);

                    Date d = new Date();
                    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm");
                    String endTime = sbf.format(d);

                    SimpleDateFormat sbfd = new SimpleDateFormat("yyyy-MM-dd");

                    //null null null 08:36
                    inserData(sbfd.format(d), null, null, endTime, eventType);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void inserData(String day, String week, String startTime, String endTime, int type) {

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                saveLog(day + "##" + week + "##" + startTime + "##" + endTime + "##" + type + "##" + System.currentTimeMillis()
                        + "\n");

                String fileName = String.format(PATH_DATE, day.substring(0, day.lastIndexOf("-")));
                if (!isNull(startTime)) {
                    //其他点击，获取早班时间
                    Gson gson = new Gson();
                    List<WorkTime> workTimes=null;
                    if (FileUtils.isFileExist(fileName)) {
                        String fileStr = FileUtils.readFile(fileName, "UTF-8").toString();

                        workTimes = gson.fromJson(fileStr,
                                new TypeToken<List<WorkTime>>() {
                                }.getType());
                        if (workTimes != null && workTimes.size() > 0) {
                            WorkTime workTime = workTimes.get(workTimes.size() - 1);
                            if (day.equalsIgnoreCase(workTime.getDay())) {
                                workTime.setWeek(week);
                                workTime.setStartTimeStr(startTime);
                                workTime.generateIndex();
                                workTimes.remove(workTimes.size() - 1);
                                workTimes.add(workTime);
                                saveWorkTimes(fileName,
                                        workTimes
                                );
                                return;
                            }
                        }
                    }
                    if (workTimes == null)
                        workTimes = new ArrayList<>();
                    WorkTime workTime = new WorkTime(day, week, startTime, endTime);
                    workTime.generateIndex();
                    workTimes.add(workTime);
                    saveWorkTimes(fileName,
                            workTimes
                    );
                } else if (!isNull(endTime)) {
                    //下班打卡,获取下班时间

                    String fileStr = FileUtils.readFile(fileName, "UTF-8").toString();
                    Gson gson = new Gson();
                    List<WorkTime> workTimes = gson.fromJson(fileStr,
                            new TypeToken<List<WorkTime>>() {
                            }.getType());
                    if (workTimes != null && workTimes.size() > 0) {
                        WorkTime workTime = workTimes.get(workTimes.size() - 1);
                        if (day.equalsIgnoreCase(workTime.getDay())) {
                            workTime.setEndTimeStr(endTime);
                            workTime.generateWorkTime();
                            workTimes.remove(workTimes.size() - 1);
                            workTimes.add(workTime);
                            saveWorkTimes(fileName,
                                    workTimes
                            );
                            return;
                        }
                        saveLog("err !" + "\n");
                    }
                } else {

                }
            }
        });
    }

    private void saveLog(String log) {
        Log.d(TAG, log);
        FileUtils.writeFile(PATH_LOG,
                log, true);
    }

    private void saveWorkTimes(String fileName, List<WorkTime> workTimes) {
        Log.d(TAG, "save " + fileName);
        Gson gson=new Gson();
        FileUtils.writeFile(fileName, gson.toJson(workTimes), false);
    }

    private static boolean isNull(String date) {
        return date == null || "null".equalsIgnoreCase(date);
    }

    @Override
    public void onInterrupt() {

    }

    private String getValue(List<AccessibilityNodeInfo> startTimeLists) {
        if (startTimeLists != null && startTimeLists.size() > 0) {
            return startTimeLists.get(0).getText().toString();
        }
        return null;
    }
}